﻿using System;
using System.Threading;
using System.Diagnostics;

namespace CxExtension.Threadding
{
	public static class ThreadUtility
	{
		/// <summary>
		/// 按照一定fps轮询的线程函数 如果func返回false 则退出函数循环
		/// </summary>
		/// <param name="fps"></param>
		/// <param name="func"></param>
		public static void ProcByFps(int fps,Func<bool> func)
		{
			bool result = false;
			int remain = 0, usedtime = 0, total = 1000 / fps;
			var watch = new Stopwatch();
			do
			{
				watch.Start();
				result = func();
				watch.Stop();
				usedtime = (int)watch.ElapsedMilliseconds;
				if(usedtime > 500)
				{
					//Debug.Print("used too time in thread {0} ,usedtime = {1}",func.Method.Name,usedtime);
				}
				remain = total - usedtime;
				if(remain > 0)
				{
					Thread.Sleep(remain);
				}
			} while(result);
		}
	}
}
